<?
include "config.inc.php";
include "utils.inc.php";

if (!isset($_REQUEST['u'])) {
  header('Location: '.$base_url.'/');
  return;
}

$url = normalize_url($_REQUEST['u']);

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, 0);
set_curl_useragent($curl);
$str = curl_exec($curl);
curl_close($curl);

$level = 0;
if (isset($_REQUEST['level'])) {
  $level = (int) $_REQUEST['level'];
}

$title = el_iextract($str, '<title>', '</title>');
echo '<ul title="'.$title.'" selected="true">';

while ($str) {
  $line = el_iextract($str, '<a ', '</a>', true);
  $str = el_iextract(el_iextract($str, '</a>'), '<a ', '', true);

  if ($line) {
    $line = str_replace('<br>', '', $line);
    if (preg_match('/ href="([^"]+)"/', $line, $res) > 0) {
      $newhref = $href = $res[1];
      // remove token from url
      $newhref = preg_replace('/[\?|&]aToken=[^&]*/', '', $newhref);
      if (strncmp($href, 'http://', 7) != 0 && strncmp($href, 'https://', 8) != 0 && strncmp($href, '/', 1) != 0) {
        // $href is relative path, add the directory
        $newhref = pathinfo(parse_url($url, PHP_URL_PATH), PATHINFO_DIRNAME).'/'.$newhref;
      }

      // if level == 0, directly go to content page
      if ($level === 0) {
        $line = str_replace($href, 'content.php?u='.urlencode($newhref), $line);
      }
      else {
        $line = str_replace($href, 'list.php?'.($level===1?'':'level='.($level - 1).'&amp;').'u='.urlencode($href), $line);
      }
    }
    echo '<li>'.$line.'</li>';
  }
}
echo '</ul>';
?>